import React from 'react';
import { Modal, Button } from 'antd';
import EditableTable from "./editableTable/editableTable";
import { openNotificationWithIcon } from '../../../../utils/comm';

class DealForm extends React.PureComponent {

  state = {
  dataSource: [],
  count: 0,
};

  openNotificationWithIcon = openNotificationWithIcon;

  handleOk = (e) => {
    if (e && e.preventDefault) e.preventDefault();
    const { dispatch, procDefKey } = this.props;
    const { dataSource } = this.state;
    if (!dataSource) return;
    const codes = {}
    const cached = {}
    let keyDuplicated = false;
    dataSource.map((item) => {
      const trimmedKey = (item.code || '').trim();
      if (cached[trimmedKey]) {
        keyDuplicated = trimmedKey;
      }
      codes[item.code] = item.nub;
      cached[trimmedKey] = 1;
      return null
  })
    if (keyDuplicated) {
      this.openNotificationWithIcon('error', '',`参数编码"${keyDuplicated}"重复`);
      return;
    }
    const params = { variables: codes, processDefinitionKey:procDefKey };
      dispatch({ type: "FlowExecution/processStart", payload: params}).then((data) => {
        const { errCode } = data;
        if (errCode === 0) {
          this.openNotificationWithIcon('success', '', '申请成功');
          this.handleCancel(false);
          // form.resetFields();
        }
      });

  }

  handleCancel = (isQuery) => {
    const { handleCancel } = this.props;
    handleCancel(false, '',isQuery);
  }

  handleTableSourceChange = (newData, count)=>{
    this.setState({ dataSource: newData });
    if (count) {
      this.setState({ count });
    }
  }

  renderFooter = (isView, confirmLoading) => {
    return (
      <div>
        <Button style={{ marginRight: 10 }} onClick={() => { this.handleCancel(false) }}>{`${isView ? '返回' : '取消'}`}</Button>
        {!isView && <Button loading={confirmLoading} type="primary" onClick={() => { this.handleOk() }}>确定</Button>}
      </div>
    )
  }

  render() {
    const { visible, title, disable, confirmLoading } = this.props;
    const { dataSource, count}=this.state;
    return (
      <Modal
        title={title || '发起申请'}
        visible={visible}
        onOk={this.handleOk}
        onCancel={() => { this.handleCancel(false) }}
        footer={this.renderFooter(disable, confirmLoading)}
        width='582px'
        centered
        confirmLoading={confirmLoading}
      >
        <EditableTable handleTableSourceChange={this.handleTableSourceChange} dataSource={dataSource} count={count} />
      </Modal>
    );
  }
}
export default DealForm;